﻿using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;

namespace DataSyncCommon
{
    /// <summary>
    /// WebService通用方法
    /// </summary>
    public class WebServiceHelper
    {
        public static XmlDocument PostWebService(string URL, string MethodName, Hashtable Pars)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "/" + MethodName);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000000;

            #region 参数拼接成字符串，最后编码
            StringBuilder sb = new StringBuilder();
            foreach (string k in Pars.Keys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }

                var value = Pars[k].ToString();
                value = HttpUtility.HtmlEncode(value);
                sb.Append(HttpUtility.UrlEncode(k) + "=" + value);
            }
            byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
            #endregion

            #region  把编码后的参数写入请求流中
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
            #endregion

            #region 读取结果，创建XmlDocument对象，对象加载结果
            var response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string retXml = sr.ReadToEnd();
            retXml = HttpUtility.HtmlDecode(retXml);
            sr.Close();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(retXml);
            #endregion

            return doc;
        }

    }
}
